﻿using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using iTextSharp.text;

namespace ProjectStudy.iTextSharpHeader
{
    public class HeaderFooter:PdfPageEventHelper,IPdfPageEvent
    {
        PdfContentByte cb;
        PdfTemplate template1;//页码模板
        PdfTemplate template2;//页眉模板
        string oddHeader = "这是奇数页眉";
        string evenHeader = "这是偶数页眉";
        BaseFont baseFont = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        
        public override void OnOpenDocument(PdfWriter writer, Document document) 
        { 
            cb = writer.DirectContent; 
            template1 = cb.CreateTemplate(50, 50);
            template2 = cb.CreateTemplate(50, 50);

        }
        public override void OnEndPage(PdfWriter writer, global::iTextSharp.text.Document document)
        {
            base.OnEndPage(writer, document);
                       
            iTextSharp.text.Font font_zhCN = new iTextSharp.text.Font(baseFont, 9);

            int currPage = writer.PageNumber; //当前页
            string text = "第" + currPage.ToString() + "页，共"; 
             
            iTextSharp.text.Rectangle pageSize = document.PageSize; 
            cb.SetRGBColorFill(100, 100, 100); 
            cb.BeginText(); 
            
            cb.SetFontAndSize(baseFont,9f);

            float len = baseFont.GetWidthPoint(text, 9f);
            cb.SetTextMatrix((document.PageSize.Width - len) / 2f, pageSize.GetBottom(document.BottomMargin)); 
            cb.ShowText(text); 
            //cb.EndText();
            cb.AddTemplate(template1, (document.PageSize.Width + len) / 2f, pageSize.GetBottom(document.BottomMargin));
           
            cb.SetTextMatrix((document.PageSize.Width - len) / 2f, pageSize.GetTop(document.TopMargin));
            if (currPage % 2 == 0)
            {
                cb.ShowText(evenHeader);
            }
            else
            {
                cb.ShowText(oddHeader);
            }
            cb.EndText();
            cb.AddTemplate(template2, (document.PageSize.Width + len) / 2f, pageSize.GetTop(document.TopMargin));
            /*
            页码位置：居左：
            ①document.LeftMargin 
            ②document.LeftMargin + len 
            居中：
            ①(document.PageSize.Width - len)/2f 
            ②(document.PageSize.Width + len)/2f 
            居右：
            ①document.PageSize.Width - len - document.RightMargin 
            ②document.PageSize.Width - document.RightMargin
             */
        }

        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            base.OnCloseDocument(writer, document);

            template1.BeginText(); 
            template1.SetFontAndSize(baseFont, 9f); 
            template1.SetTextMatrix(0, 0); 
            template1.ShowText("" + writer.PageNumber+"页"); 
            template1.EndText();
        }
    }
}